import React, { useEffect, useMemo, useState } from 'react';
import { Breadcrumb, Layout, theme } from 'antd';
import { useLocation, Route, BrowserRouter as Router, Routes, Outlet } from 'react-router-dom';
import { AppstoreOutlined, MailOutlined, SettingOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import zhanzhangImg from './assets/imgs/1.jpg';
import { useSelector, useDispatch } from 'react-redux';
import { setStandingList,setsidebarList,setcity,coordinate } from './store/model/counter';
import request from './utils/axios'
declare var AMap: any;

const { Header, Content, Sider } = Layout;

const App: React.FC = () => {
  const dispatch = useDispatch();
  const [city,setCity]=useState('')
  const { standingId, standingList, standingName } = useSelector((store: any) => store.counter);

  const location = useLocation();
  const getHeight = () => {
    switch (location.pathname) {
      case '/app/scheduling':
        return '160vh';
      case '/app/shedulingadd':
        return '120vh';
      case '/app/standingadd':
        return '120vh';
      case '/app/standingedit':
        return '120vh';
      case '/app/distribution':
        return '135vh';
      case '/app/operation':
        return '120vh';
      case '/app/personal':
        return '120vh';
      default:
        return '100vh';
    }
  };

  const {token: { colorBgContainer, borderRadiusLG }} = theme.useToken();

  const onClick: MenuProps['onClick'] = (e) => {
    window.location.href = e.key;
  };

  function removeLevelThreeChildren(data: any) {
    return data.map((item: any) => {
      const newItem = { ...item };

      // 如果当前项有 children 属性，则递归处理 children
      if (item.children) {
        newItem.children = removeLevelThreeChildren(item.children).filter((child: any) => child.level !== 3);
      }

      // 如果当前项的 level 等于 2，则删除 children 字段
      if (newItem.level === 2) {
        delete newItem.children;
      }

      return newItem;
    }).filter((item: any) => item.level !== 3); // 最后一步过滤掉 level 为3的项
  }

  const [sidebarList, setSidebarList] = useState([]);
  const [standinglist, setStandinglist] = useState([]);

  // 根据身份获取权限id
  
  const getStanding = async () => {
    request.get('getstanding',{_id: standingId,}).then(error=>{
      console.log(error,'app');
    }).catch(response=>{
      setStandinglist(response.data.standingList[0].authority);
      dispatch(setStandingList(response.data.standingList[0].authority));
      if (standingList) {
        getSidebarList();
      }
    })
  };

  const newlist = useMemo(() => {
    let list: any = [];
    standingList.forEach((item: any) => {
      list.push(item._id);
    });
    return list;
  }, [standinglist]);

  const newAuthorityList = useMemo(() => {
    let list: any = [];
    standingList.forEach((item: any) => {
      list.push(item.key);
    });
    return list;
  },[standinglist])

  // 获取权限列表
  const getSidebarList = async () => {
    request.get('getauthority',{idList: newlist}).then(error=>{
      console.log(error);
    }).catch(response=>{
      setSidebarList(response.data.authorityList);
    })
  };

  //获取当前定位
  const getcity=()=>{
    var geocoder = new AMap.Geocoder({
      city: "010", //城市设为北京，默认：“全国”
      radius: 1000 //范围，默认：500
    });
    AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：5s
            buttonPosition:'RB',    //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

        });
        geolocation.getCurrentPosition(function(status:any,result:any){
            if(status=='complete'){
                onComplete(result)
            }else{
                onError(result)
            }
        });
    });
    //解析定位结果
    function onComplete(data:any) {
        var str = [];
        str.push('定位结果：' + data.position);
        str.push('定位类别：' + data.location_type);
        if(data.accuracy){
             str.push('精度：' + data.accuracy + ' 米');
        }//如为IP精确定位结果则没有精度信息
        str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
        dispatch(coordinate([data.position.KL,data.position.kT]))
        
        geocoder.getAddress(data.position, function(status:any,result:any) {
            if (status === 'complete'&&result.regeocode) {
                var address = result.regeocode.formattedAddress;
                setCity(address)
                dispatch(setcity(address))
            }else{
                console.log('根据经纬度查询地址失败')
            }
        });
    }
    //解析定位错误信息
    function onError(data:any) {
        console.log(data);
    }
  }

  const filteredList = useMemo(() => removeLevelThreeChildren(sidebarList), [sidebarList]);

  useEffect(() => {
    getStanding();
    if(newAuthorityList.length!=0){
      dispatch(setsidebarList(newAuthorityList));
    }
    getcity()
  }, []);

  return (
    <Layout style={{ height: getHeight() }}>
            <Header style={{ display: 'flex', alignItems: 'center' }}>
              <div className="demo-logo" />
              <Menu
                theme="dark"
                mode="horizontal"
                defaultSelectedKeys={['2']}
                items={filteredList}
                style={{ flex: 1, minWidth: 0 }}
              />
              <div style={{color:'#fff'}}>{city}</div>
            </Header>
            <Layout>
              <Sider width={200} style={{ background: colorBgContainer }}>
                <div>
                  <img
                    src={zhanzhangImg}
                    style={{ width: '5em', height: '5em', borderRadius: '50%' }}
                  />
                </div>
                <Menu
                  onClick={onClick}
                  style={{ width: 200 }}
                  defaultSelectedKeys={['1']}
                  defaultOpenKeys={['sub1']}
                  mode="inline"
                  items={filteredList}
                />
              </Sider>
              <Layout style={{ padding: '24px 24px' }}>
                <Content
                  style={{
                    padding: 12,
                    margin: 0,
                    minHeight: 280,
                    background: colorBgContainer,
                    borderRadius: borderRadiusLG,
                  }}
                >
                  <Outlet />
                </Content>
              </Layout>
            </Layout>
    </Layout>
  );
};

export default App;